package com.ewins.weatherdataclient.downloadmodule;

//import com.ewins.weatherdataclient.beans.DownloadStateBean;

import com.ewins.weatherdataclient.common.Constant;
import com.ewins.weatherdataclient.https.HttpsDefault;
import com.ewins.weatherdatautils.bean.DownloadStateBean;
import com.ewins.weatherdatautils.bean.SiteInfoBean;
import com.ewins.weatherdatautils.utils.Utils;
import com.google.common.eventbus.EventBus;
import org.apache.log4j.Logger;

import javax.net.ssl.HttpsURLConnection;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;

public class FileSplitterFetchHttp extends Thread {
	Logger log=Logger.getLogger(FileSplitterFetchHttp.class);

	//String sURL; // File URL
	//String sName;
	long nStartPos; // File Snippet Start Position
	long nEndPos; // File Snippet End Position
	int nThreadID; // Thread's ID
	boolean bDownOver = false; // Downing is over
	boolean bStop = false; // Stop identical
	FileAccessI fileAccessI = null; // File Access interface
	SiteInfoBean siteInfoBean;
	EventBus eventBus;
	DownloadStateBean ds=new DownloadStateBean();

//	public FileSplitterFetchHttp(String sURL, String sName, long nStart, long nEnd,
//								 int id, EventBus eventBus) throws IOException {
//		this.sURL = sURL;
//		this.nStartPos = nStart;
//		this.nEndPos = nEnd;
//		nThreadID = id;
//		fileAccessI = new FileAccessI(sName, nStartPos);
//
//		this.eventBus=eventBus;
//	}

	public FileSplitterFetchHttp(SiteInfoBean siteInfoBean, long nStart, long nEnd,
								 int id, EventBus eventBus) throws IOException {

//		this.sURL = siteInfoBean.getSSiteURL();
//		this.sName= siteInfoBean.getSFilePath()+ File.separator + siteInfoBean.getSFileName();
		this.siteInfoBean=siteInfoBean;
		this.nStartPos = nStart;
		this.nEndPos = nEnd;
		nThreadID = id;
		fileAccessI = new FileAccessI(siteInfoBean.getSFilePath()+ File.separator + siteInfoBean.getSFileName()+".tmp", nStartPos);
		this.eventBus=eventBus;
	}

	public void run() {

		String sURL = siteInfoBean.getSSiteURL();
		InputStream input=null;
		while (nStartPos < nEndPos && !bStop) {
			try {
				URL url = new URL(siteInfoBean.getSSiteURL());
				//HttpsDefault.setDefaultValue();
				HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
				//httpsConnection.setSSLSocketFactory(HttpsDefault.getSSLSocketFactory());
				httpConnection.setRequestProperty("User-Agent", "NetFox");
				String sProperty = "bytes=" + nStartPos + "-";
				httpConnection.setRequestProperty("RANGE", sProperty);
//				log.info(sProperty);
				 input = httpConnection.getInputStream();
				//logResponseHead(httpConnection);
				byte[] b = new byte[1024];
				int nRead;
				while ((nRead = input.read(b, 0, 1024)) > 0
						&& nStartPos < nEndPos && !bStop) {
					nStartPos += fileAccessI.write(b, 0, nRead);
					// if(nThreadID == 1)
					// Utility.log("nStartPos = " + nStartPos + ", nEndPos = " +
					// nEndPos);
				}
				System.out.println(siteInfoBean.getSFileName()+":Thread " + nThreadID + " is over!");
				bDownOver = true;
				httpConnection.disconnect();
				//fileAccessI.close();
				// nPos = fileAccessI.write (b,0,nRead);
			}catch (UnknownHostException e){
				//服务器url错误
				ds.setFileError("服务器url不存在");
				ds.setIsContinue(true);
				ds.setIsDownload("T");
				eventBus.post(ds);
				log.error("UnknownHostException: " + e.getMessage());
				//break;
			} catch (SocketException e){
					//网络连接异常
					ds.setFileError("网络无法连接");
					ds.setIsContinue(true);
					ds.setIsDownload("T");
					eventBus.post(ds);
					log.error("SocketException: "+siteInfoBean.getSFileName() + e.getMessage());

			}catch (IOException e){
				//文件不存在异常
				ds.setFileError("网络无法连接");
				ds.setIsContinue(true);
				ds.setIsDownload("T");
				eventBus.post(ds);
				log.error("IOException: " +siteInfoBean.getSFileName()+ e.getMessage());
			}catch (Exception e){
				//网络连接异常
				ds.setFileError("Exception"+e.getMessage());
				ds.setIsContinue(true);
				ds.setIsDownload("T");
				eventBus.post(ds);
				log.error("Exception: "+siteInfoBean.getSFileName() + e.getMessage());
			}
		}

		if(nStartPos>=nEndPos){
			try {
				if(input!=null) {
					//删除.info记录文件
					input.close();
					fileAccessI.close();
					Utils.deleteRemoteFile(siteInfoBean, ".info");
					File f=new File(siteInfoBean.getSFilePath()+siteInfoBean.getSFileName()+".tmp");
					f.renameTo(new File(f.getAbsolutePath().substring(0,f.getAbsolutePath().lastIndexOf(".tmp"))));
				}
			}
			catch (Exception e) {
				log.error(e.getMessage());
			}
		}
	}

	public void logResponseHead(HttpURLConnection con) {
		for (int i = 1;; i++) {
			String header = con.getHeaderFieldKey(i);
			if (header != null)
				// responseHeaders.put(header,httpConnection.getHeaderField(header));
				//Utility.log(header + " : " + con.getHeaderField(header));
				log.info(header + " : " + con.getHeaderField(header));
			else
				break;
		}
	}

	public void splitterStop() {
		fileAccessI.close();
		bStop = true;
	}
}
